package com.yl.immodule.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.DownsampleStrategy;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.camera.base.util.FileUtil;
import com.camera.base.util.ToastUtil;
import com.camera.routemodule.RouterPath;
import com.hm.poc.http.HttpSenderManager;
import com.yl.immodule.APP;
import com.yl.immodule.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;
import java.util.function.Function;

public class ImageMessageView extends FrameLayout {
    private static final String TAG = "ImageMessageView";
    
    // 进一步减小尺寸限制
    private static final int MAX_IMAGE_WIDTH = 200;  // 缩小到200px
    private static final int MAX_IMAGE_HEIGHT = 200; // 缩小到200px
    private static final int MIN_IMAGE_SIZE = 80;    // 最小尺寸也相应减小
    private static final float THUMBNAIL_SCALE = 0.3f; // 增加缩略图比例，使预览更清晰
    
    private ImageView thumbnailView;
    private ProgressBar progressBar;
    private TextView errorText;
    private TextView progressText;
    private View progressOverlay;
    private View progressContainer;
    private int retryCount = 0;
    private static final int MAX_RETRY = 2;
    
    // 保存当前正在显示的图片路径
    private String currentImagePath = "";
    
    // 优化的RequestOptions配置
    private static final RequestOptions COMMON_OPTIONS = new RequestOptions()
        .format(DecodeFormat.PREFER_RGB_565) // 使用RGB565格式，减少内存占用
        .downsample(DownsampleStrategy.CENTER_INSIDE) // 使用更高效的采样策略
        .diskCacheStrategy(DiskCacheStrategy.ALL)
        .skipMemoryCache(false) // 启用内存缓存
        .placeholder(R.drawable.ic_image_placeholder)
        .error(R.drawable.ic_image_error);
    
    public ImageMessageView(Context context) {
        super(context);
        init(context);
    }
    
    public ImageMessageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }
    
    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.view_image_message, this, true);
        thumbnailView = findViewById(R.id.image_thumbnail);
        progressBar = findViewById(R.id.progress_bar);
        errorText = findViewById(R.id.error_text);
        progressText = findViewById(R.id.progress_text);
        progressOverlay = findViewById(R.id.progress_overlay);
        progressContainer = findViewById(R.id.progress_container);
        
        thumbnailView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        thumbnailView.setAdjustViewBounds(true);
        
        // 设置图片点击事件
        thumbnailView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openImageGallery();
            }
        });
    }
    
    /**
     * 打开图片查看界面
     */
    private void openImageGallery() {
        if (currentImagePath != null && !currentImagePath.isEmpty()) {
            // 确保是本地文件路径
            if (new File(currentImagePath).exists()) {
                // 使用ARouter跳转到图片查看界面
                ARouter.getInstance()
                       .build(RouterPath.path.gallery_activity)
                       .withString("path", currentImagePath)
                       .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                       .navigation();
            } else if (isNetworkImage(currentImagePath)) {
                // 如果是网络图片，可能需要先下载或直接查看
                Toast.makeText(getContext(), "正在加载图片，请稍后再试", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getContext(), "图片不存在", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getContext(), "没有可查看的图片", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 判断是否是网络图片URL
     */
    private boolean isNetworkImage(String imagePath) {
        return imagePath != null && (imagePath.startsWith("http://") || imagePath.startsWith("https://"));
    }
    
    /**
     * 处理HTTP URL，确保能够正确加载
     */
    private String processUrl(String url) {
        if (url == null || url.isEmpty()) {
            return url;
        }
        
        try {
            return url.replace(" ", "%20");
        } catch (Exception e) {
            Log.e(TAG, "处理URL失败: " + e.getMessage());
            return url;
        }
    }
    
    /**
     * 加载图片
     * @param imagePath 图片路径
     * @param progress 进度
     * @param savedPathCallback 网络图片保存后的路径回调
     */
    public void loadImage(boolean isOut,String imagePath, int progress, Function<String, Void> savedPathCallback) {
        if (imagePath == null || imagePath.isEmpty()) {
            setError("图片路径为空");
            return;
        }
        
        // 保存当前正在显示的图片路径
        this.currentImagePath = imagePath;
        
        retryCount = 0;
        boolean isNetworkImage = isNetworkImage(imagePath);
        Log.d(TAG, "加载图片: " + imagePath + ", 是否网络图片: " + isNetworkImage + ", 进度: " + progress);
        
        if (isNetworkImage) {
            String processedUrl = processUrl(imagePath);
            loadNetworkImage(processedUrl, savedPathCallback);
        } else {
            loadLocalImage(isOut,imagePath, progress);
        }
    }
    /**
     * 加载网络图片
     */
    private void loadNetworkImage(String url, Function<String, Void> savedPathCallback) {
        showProgress(0);
        
        RequestOptions options = COMMON_OPTIONS
            .clone()
            .override(MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT);
            
        try {
            Glide.with(getContext())
                .load(url + "?authorization=" + HttpSenderManager.INSTANCE.getToken())
                .thumbnail(
                    Glide.with(getContext())
                        .load(url + "?authorization=" + HttpSenderManager.INSTANCE.getToken())
                        .override(MAX_IMAGE_WIDTH / 2, MAX_IMAGE_HEIGHT / 2)
                )
                .apply(options)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        Log.e(TAG, "网络图片下载失败: " + e.getMessage());
                        
                        if (retryCount < MAX_RETRY) {
                            retryCount++;
                            Log.d(TAG, "重试加载图片 (" + retryCount + "/" + MAX_RETRY + "): " + url);
                            
                            if (retryCount == 1) {
                                hideProgress();
                                loadWithFile(url);
                                return true;
                            }
                        } else {
                            hideProgress();
                            setError("图片加载失败");
                        }
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        Log.d(TAG, "网络图片下载完成");
                        hideProgress();
                        
                        // 获取图片尺寸并设置
                        int width = resource.getIntrinsicWidth();
                        int height = resource.getIntrinsicHeight();
                        int[] scaledDimensions = calculateScaledDimensions(width, height);
                        setImageViewDimensions(scaledDimensions[0], scaledDimensions[1]);
                        
                        // 保存图片并返回路径
                        new Thread(() -> {
                            try {
                                // 将Drawable转换为Bitmap
                                Bitmap bitmap;
                                if (resource instanceof BitmapDrawable) {
                                    bitmap = ((BitmapDrawable) resource).getBitmap();
                                } else {
                                    bitmap = Bitmap.createBitmap(resource.getIntrinsicWidth(), 
                                            resource.getIntrinsicHeight(), 
                                            Bitmap.Config.ARGB_8888);
                                    Canvas canvas = new Canvas(bitmap);
                                    resource.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                                    resource.draw(canvas);
                                }

                                // 生成文件名和路径
                                String timeStamp = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.getDefault()).format(new Date());
                                String fileName = "IMG_" + timeStamp + ".jpg";
                                String savePath = FileUtil.INSTANCE.getBaseCaptureIMPath();
                                File imageFile = new File(savePath, fileName);

                                // 保存图片
                                try (FileOutputStream fos = new FileOutputStream(imageFile)) {
                                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                                    fos.flush();
                                }

                                Log.d(TAG, "图片已保存到: " + imageFile.getAbsolutePath());
                                
                                // 更新当前图片路径为本地路径
                                currentImagePath = imageFile.getAbsolutePath();

                                // 如果bitmap是新创建的，需要回收
                                if (!(resource instanceof BitmapDrawable)) {
                                    bitmap.recycle();
                                }

                                // 回调保存的路径
                                if (savedPathCallback != null) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                        post(() -> savedPathCallback.apply(imageFile.getAbsolutePath()));
                                    }
                                }
                            } catch (Exception e) {
                                Log.e(TAG, "保存图片失败: " + e.getMessage());
                            }
                        }).start();
                        
                        return false;
                    }
                })
                .into(thumbnailView);
        } catch (Exception e) {
            Log.e(TAG, "加载图片异常: " + e.getMessage());
            setError("图片加载异常");
        }
    }
    
    /**
     * 使用File对象尝试加载
     */
    private void loadWithFile(String url) {
        try {
            Uri uri = Uri.parse(url);
            
            RequestOptions options = COMMON_OPTIONS
                .clone()
                .override(MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT);
                
            Glide.with(getContext())
                .load(uri)
                .thumbnail(
                    Glide.with(getContext())
                        .load(uri)
                        .override(MAX_IMAGE_WIDTH / 2, MAX_IMAGE_HEIGHT / 2)
                )
                .apply(options)
                .into(thumbnailView);
        } catch (Exception e) {
            Log.e(TAG, "File加载方式失败: " + e.getMessage());
            setError("图片加载失败");
        }
    }
    
    /**
     * 加载本地图片
     */
    private void loadLocalImage(boolean isOut,String imagePath, int progress) {
        File file = new File(imagePath);
        if (!file.exists()) {
            Log.e(TAG, "本地文件不存在: " + imagePath);
            if (progress > 0 && progress < 100) {
                showProgress(progress);
            } else {
                setError("图片文件不存在");
            }
            return;
        }
        
        RequestOptions options = COMMON_OPTIONS
            .clone()
            .override(MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT);
            
        Glide.with(getContext())
            .load(file)
            .thumbnail(
                Glide.with(getContext())
                    .load(file)
                    .override(MAX_IMAGE_WIDTH / 2, MAX_IMAGE_HEIGHT / 2)
            )
            .apply(options)
            .listener(new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    Log.e(TAG, "本地图片加载失败: " + e.getMessage());
                    setError("图片加载失败");
                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                    int width = resource.getIntrinsicWidth();
                    int height = resource.getIntrinsicHeight();
                    int[] scaledDimensions = calculateScaledDimensions(width, height);
                    setImageViewDimensions(scaledDimensions[0], scaledDimensions[1]);
                    
                    return false;
                }
            })
            .into(thumbnailView);
        
        if (progress < 100 && isOut) {
            showProgress(progress);
        } else {
            hideProgress();
        }
    }
    
    /**
     * 计算等比例缩放后的尺寸
     */
    private int[] calculateScaledDimensions(int originalWidth, int originalHeight) {
        float ratio = (float) originalWidth / originalHeight;
        int scaledWidth, scaledHeight;
        
        if (originalWidth > originalHeight) {
            scaledWidth = Math.min(MAX_IMAGE_WIDTH, Math.max(originalWidth, MIN_IMAGE_SIZE));
            scaledHeight = (int) (scaledWidth / ratio);
            
            // 确保高度不超过最大限制
            if (scaledHeight > MAX_IMAGE_HEIGHT) {
                scaledHeight = MAX_IMAGE_HEIGHT;
                scaledWidth = (int) (scaledHeight * ratio);
            }
        } else {
            scaledHeight = Math.min(MAX_IMAGE_HEIGHT, Math.max(originalHeight, MIN_IMAGE_SIZE));
            scaledWidth = (int) (scaledHeight * ratio);
            
            // 确保宽度不超过最大限制
            if (scaledWidth > MAX_IMAGE_WIDTH) {
                scaledWidth = MAX_IMAGE_WIDTH;
                scaledHeight = (int) (scaledWidth / ratio);
            }
        }
        
        return new int[]{scaledWidth, scaledHeight};
    }
    
    /**
     * 设置ImageView的尺寸
     */
    private void setImageViewDimensions(int width, int height) {
        LayoutParams params = (LayoutParams) thumbnailView.getLayoutParams();
        if (params == null) {
            params = new LayoutParams(width, height);
        } else {
            params.width = width;
            params.height = height;
        }
        thumbnailView.setLayoutParams(params);
        
        // 同步设置遮罩层和进度容器的尺寸
        syncOverlayDimensions(width, height);
    }
    
    /**
     * 同步遮罩层和进度容器的尺寸，使其与图片尺寸一致
     */
    private void syncOverlayDimensions(int width, int height) {
        // 设置遮罩层尺寸
        LayoutParams overlayParams = (LayoutParams) progressOverlay.getLayoutParams();
        if (overlayParams == null) {
            overlayParams = new LayoutParams(width, height);
        } else {
            overlayParams.width = width;
            overlayParams.height = height;
        }
        progressOverlay.setLayoutParams(overlayParams);
        
        // 设置进度容器尺寸
        LayoutParams containerParams = (LayoutParams) progressContainer.getLayoutParams();
        if (containerParams == null) {
            containerParams = new LayoutParams(width, height);
        } else {
            containerParams.width = width;
            containerParams.height = height;
        }
        progressContainer.setLayoutParams(containerParams);
        
        Log.d(TAG, "同步遮罩层尺寸: " + width + "x" + height);
    }
    
    private void showProgress(int progress) {
        // 确保遮罩层尺寸与图片一致
        ensureOverlayDimensions();
        
        progressOverlay.setVisibility(View.VISIBLE);
        progressContainer.setVisibility(View.VISIBLE);
        progressBar.setProgress(progress);
        progressText.setText(progress + "%");
        errorText.setVisibility(View.GONE);
    }
    
    /**
     * 确保遮罩层尺寸与当前图片尺寸一致
     */
    private void ensureOverlayDimensions() {
        // 获取ImageView的当前尺寸
        int width = thumbnailView.getWidth();
        int height = thumbnailView.getHeight();
        
        // 如果ImageView还没有测量完成，使用layoutParams中的尺寸
        if (width == 0 || height == 0) {
            LayoutParams imageParams = (LayoutParams) thumbnailView.getLayoutParams();
            if (imageParams != null) {
                width = imageParams.width > 0 ? imageParams.width : MIN_IMAGE_SIZE;
                height = imageParams.height > 0 ? imageParams.height : MIN_IMAGE_SIZE;
            } else {
                // 使用默认最小尺寸
                width = MIN_IMAGE_SIZE;
                height = MIN_IMAGE_SIZE;
            }
        }
        
        Log.d(TAG, "确保遮罩层尺寸: " + width + "x" + height);
        syncOverlayDimensions(width, height);
    }
    
    private void hideProgress() {
        progressOverlay.setVisibility(View.GONE);
        progressContainer.setVisibility(View.GONE);
        errorText.setVisibility(View.GONE);
    }
    
    public void setError(String errorMsg) {
        // 确保遮罩层尺寸与图片一致
        ensureOverlayDimensions();
        
        progressOverlay.setVisibility(View.VISIBLE);
        progressContainer.setVisibility(View.GONE);
        errorText.setVisibility(View.VISIBLE);
        errorText.setText(errorMsg);
    }
} 